import axios from "axios";
import IndexedDBManager from "./IndexedDBManager.js";


const db = new IndexedDBManager('db', '1.0', 'stock')
db.openDB()

const getCode = (code) => {
    if (code === '000000') {
        return '1.000001'
    } else if (code.startsWith('BK')) {
        return '90.' + code
    } else if (code.startsWith('6')) {
        return '1.' + code
    } else {
        return '0.' + code
    }
}

export const getLocalData = (option, cb) => {
    let typeArr = localStorage.getItem(option.type)
    if(typeArr) {
        let arr = JSON.parse(typeArr)
        let line = arr.filter(item => item.code === option.code)
        if(line.length) {
            cb(line[0].lines)
        } else {
            cb(null)
        }
    } else {
        cb(null)
    }
}

// 51 日期 52开盘价 53 收盘价 54 最高价 55 最低价

export const getRequestData = (option, cb, isContinue = false) => {
    let code = getCode(option.code)

    let params = {
        fields1: 'f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13',
        fields2: 'f51,f52,f53,f54,f55,f56',
        beg: '0',
        end: '20500101',
        ut: 'fa5fd1943c7b386f172d6893dbfba10b',
        rtntype: '6',
        secid: code,
        klt: option.type,
        fqt: '0', // 0 不复权 1前复权 2后复权
        cb: 'jsonp1718182461531',
    }

    db.getData(option.code).then(result => {
        if(result && result.value) {
            let line = result.value.filter(item => item.type === option.type)[0]

            if(line) {
                let hours = new Date().getHours()
                let day = new Date(line.time).getDate()

                if(new Date().getDay() !== 6 && new Date().getDay() !== 0 && (day !== new Date().getDate() || day === new Date().getDate() && (hours < 15 && hours>=13 || hours >= 9 && hours<12))) {
                    axios.get('https://push2his.eastmoney.com/api/qt/stock/kline/get', {
                        params
                    }).then(res => {
                        const str = res.data.replace('jsonp1718182461531(', '').replace(');', '');
                        const data = JSON.parse(str)

                        result.value = result.value.map(item => {
                            if(item.type === option.type) {
                                item.time = new Date().getTime()
                                item.lines = data.data
                            }
                            return item
                        })
                        db.updateData(option.code, {id:option.code, value: result.value})
                        cb(data.data)
                    }).catch((err) => {
                        if(err.code === "ERR_NETWORK") {
                            console.log('网络错误')
                        } else if (isContinue) {
                            setTimeout(() => {
                                getRequestData(option, cb)
                            },1000)
                        }
                    })
                } else {
                    cb(line.lines)
                }
            } else {
                axios.get('https://push2his.eastmoney.com/api/qt/stock/kline/get', {
                    params
                }).then(res => {
                    const str = res.data.replace('jsonp1718182461531(', '').replace(');', '');
                    const data = JSON.parse(str)
                    result.value.push({
                        type: option.type,
                        lines: data.data,
                        time: new Date().getTime()
                    })
                    db.updateData(option.code, {id: option.code, value: result.value})
                    cb(data.data)
                }).catch((err) => {
                    if(err.code === "ERR_NETWORK") {
                        console.log('网络错误')
                    } else if (isContinue) {
                        setTimeout(() => {
                            getRequestData(option, cb)
                        },1000)
                    }
                })

            }
        } else {
            axios.get('https://push2his.eastmoney.com/api/qt/stock/kline/get', {
                params
            }).then(res => {
                const str = res.data.replace('jsonp1718182461531(', '').replace(');', '');
                const data = JSON.parse(str)
                db.addData({id: option.code, value: [{type: option.type, lines: data.data, time: new  Date().getTime()}]})
                cb(data.data)
            }).catch((err) => {
                if(err.code === "ERR_NETWORK") {
                    console.log('网络错误')
                } else if (isContinue) {
                    setTimeout(() => {
                        getRequestData(option, cb)
                    },1000)
                }
            })
        }
    }).catch(e => {
        console.log(e)

    })
}


export const getStockDetail = (option, cb) => {
    let code = getCode(option.code)

    axios.get('https://2.push2.eastmoney.com/api/qt/stock/get', {
        params: {
            ut: 'fa5fd1943c7b386f172d6893dbfba10b',
            fltt: 2,
            invt: 2,
            volt: 2,
            fields: 'f152,f288,f43,f57,f58,f169,f170,f46,f44,f51,f168,f47,f164,f116,f60,f45,f52,f50,f48,f167,f117,f71,f161,f49,f530,f135,f136,f137,f138,f139,f141,f142,f144,f145,f147,f148,f140,f143,f146,f149,f55,f62,f162,f92,f173,f104,f105,f84,f85,f183,f184,f185,f186,f187,f188,f189,f190,f191,f192,f107,f111,f86,f177,f78,f110,f262,f263,f264,f267,f268,f250,f251,f252,f253,f254,f255,f256,f257,f258,f266,f269,f270,f271,f273,f274,f275,f127,f199,f128,f198,f259,f260,f261,f171,f277,f278,f279,f31,f32,f33,f34,f35,f36,f37,f38,f39,f40,f20,f19,f18,f17,f16,f15,f14,f13,f12,f11,f531,f59',
            secid: code,
            cb: 'jQuery351020868518046374174_1723545775340',
            _: '1723545775342',
        }
    }).then(res => {
        const str = res.data.replace('jQuery351020868518046374174_1723545775340(', '').replace(');', '');
        let data = JSON.parse(str)
        // 过滤掉ST股
        // data = data.data.diff.filter(item => item.f14.indexOf('ST') === -1 && item.f2 > 2)
        cb(data.data)
    })
}

// 获取股票列表
export const getStockListData = (cb) => {

    axios.get('https://5.push2.eastmoney.com/api/qt/clist/get', {
        params: {
            cb: 'jQuery1124002285341096772009_1735976655317',
            pn: 1,
            pz: 10000,
            po: 1,
            np: 1,
            ut: 'bd1d9ddb04089700cf9c27f6f7426281',
            fltt: 2,
            invt: 2,
            dect: 1,
            wbp2u: '|0|0|0|web',
            fid: 'f3',
            fs: 'm:0 t:6,m:0 t:80,m:1 t:2,m:1 t:23,m:0 t:81 s:2048',
            fields: 'f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152',
            '_': '1735976655323'
        }
    }).then(res => {
        const str = res.data.replace('jQuery1124002285341096772009_1735976655317(', '').replace(');', '');
        let data = JSON.parse(str)
        // 过滤掉ST股
        // data = data.data.diff.filter(item => item.f14.indexOf('ST') === -1 && item.f2 > 2)
        cb(data.data)
    })
}

// 行业板块
export const getStockBK = (cb) => {
    axios.get('\n' +
        'https://16.push2.eastmoney.com/api/qt/clist/get?cb=jQuery11240438024888677345_1723548437570&pn=1&pz=100&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&dect=1&wbp2u=|0|0|0|web&fid=f3&fs=m:90+t:2+f:!50&' +
        'fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f26,f22,f33,f11,f62,f128,f136,f115,f152,f124,f107,f104,f105,f140,f141,f207,f208,f209,f222&_=1723548437571').then(res => {
        const str = res.data.replace('jQuery11240438024888677345_1723548437570(', '').replace(');', '');
        let data = JSON.parse(str)
        cb(data.data.diff)
    })
}

// 期货级别详情
export const getFuturesDetail = (params, cb) => {
    axios.get(`/futures/api/jsonp.php/var%20_${params.path}`, {
        params
    }).then(res => {
        const data = JSON.parse(res.data.match(/\[.*]/)[0])
        cb(data)

    }).catch((err) => {
        console.log(err)
    })
}